<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>主页</title>
    <link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/plugins/build/css/app.css" media="all">
    <link rel="stylesheet" type="text/css" href="/plugins/webuploader/webuploader.css">
</head>
<style>
    .edit_form .layui-form-item{
        display: block;
        margin-bottom: 20px;
    }
    .uploader-box .picker{
        display: inline-block;
    }
    .uploader-box .picker .webuploader-pick{
        background: #fff;
        border: 1px solid #ccc;
        padding: 7px;
    }
    .uploader-box .picker .webuploader-pick img{
        height: 80px;
        width: 80px;;
    }
    .uploader-box .uploader-list{
        position: relative;
        display: inline-block;
    }
    .uploader-item{
        position: relative;
        margin-right: 5px;
        display: inline-block;
        border: 1px solid #ccc;
    }
    .uploader-box .uploader-list .upload-img{
        height: 100px;
        width: 100px;
        margin: 0 5px;
    }
    .uploader-box .uploader-list .del-img{
        cursor: pointer;
        width: 20px;
        height: 20px;
        padding: 3px;
        position: absolute;
        top: 0;right: 0;
        border-left: 1px solid #eee;
        border-bottom: 1px solid #eee;
        background: rgba(255, 255, 255, 0.9);
    }
</style>
<body>
<div class="container">
    <div class="module-title">
        <span class="layui-breadcrumb">
            <a href="javascript:history.go(-1);" class="back">
                <i class="layui-icon back">&#xe603;</i>
                <span class="moduleName">编辑商品</span>
            </a>
        </span>
    </div>
    <form class="layui-form  edit_form" action="">
        <input type="hidden" name="contentId" value=""/>
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-inline">
                <input style="width: 400px;" type="text" name="goodsName" required  lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">商品简介</label>
            <div class="layui-input-block">
                <input style="width: 400px;" name="goodsTitle" placeholder="" class="layui-input"></input>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品价格</label>
            <div class="layui-input-inline">
                <input style="width: 400px;" type="text" name="goodsPrice" required  lay-verify="required" placeholder="￥" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品库存</label>
            <div class="layui-input-inline">
                <input style="width: 400px;" type="text" name="goodsStock" required  lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品图片</label>
            <div class="uploader">
                <!--用来存放图片信息-->
                <div class="uploader-box">
                    <div class="uploader-list">

                    </div>
                    <div class="picker">
                        <img src="/plugins/img/add.png"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item content_btn">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="contentForm">立即提交</button>
            </div>
        </div>
    </form>
</div>
<script src="/plugins/layui/layui.js"></script>
<script src="/plugins/jquery-1.8.3.min.js"></script>
<script src="/plugins/webuploader/webuploader.js"></script>
<script src="/plugins/common.js"></script>

<script>
    var imgNum = 0;
    var uploader = WebUploader.create({
        // swf文件路径
        swf: 'http://fex.baidu.com/webuploader/js/Uploader.swf',
        // 文件接收服务端。
        server: SERVER_URL+'/shopGoods/upload',
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '.picker',
        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false,
        thumb: {
            width: 100,
            height: 100,
            type: 'image/jpg,jpeg,png',
            allowMagnify: false
        },
        accept: {
            title: 'Images',
            extensions: 'jpg,jpeg,png',
            mimeTypes: 'image/jpg,image/jpeg,image/png'
        },
        fileNumLimit: 5,
        fileSingleSizeLimit: 2048000,
        fileVal: "image",
        auto: true
    });

    //删除
    function del(_this){
        var id = $(_this).prev().attr("id");
        $(_this).parent().remove();
        uploader.removeFile(uploader.getFile(id));
        imgNum --;
    }

    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
        var li = '<div class="uploader-item">';
        li += '		<input name="upload-img-src" type="hidden" value=""/>';
        li += '		<img class="upload-img" src="" id="'+file.id+'"/>';
        li += '		<img class="del-img" src="/plugins/img/del.png" onClick="del(this)"/>'
        li += '   </div>';
        $(".uploader-list").append(li);
        uploader.makeThumb( file, function( error, src ) {
            $("#"+file.id).attr( 'src', src );
        });
        imgNum ++;
    });

    // 上传成功
    uploader.on( 'uploadSuccess', function( file, response) {
        $("#"+file.id).prev().val(JSON.parse(response._raw).data)
    });

    // 上传失败
    uploader.on( 'uploadError', function( file ) {
        console.log("上传失败:"+file.id)
    });

    // 所有图片上传完成
    uploader.on( 'uploadFinished', function() {
        var imgs = [];
        var srcs = $("input[name='upload-img-src']");
        if(srcs.length == imgNum){
            srcs.each(function(){
                imgs.push($(this).val());
            })
        }

        if(srcs.length == imgNum && imgs.length > 0){
            var goodsName = $("input[name='goodsName']").val();
            var goodsTitle = $("input[name='goodsTitle']").val();
            var goodsPrice = $("input[name='goodsPrice']").val();
            var goodsStock = $("input[name='goodsStock']").val();
            $.ajax({
                type: 'POST',
                url: editUrl,
                data: {goodsId:urlParam("id"),goodsName:goodsName,goodsTitle:goodsTitle,goodsPrice:goodsPrice,goodsStock:goodsStock,goodsImage:imgs.join(",")},
                success: function (result) {
                    if(result.code == 20000){
                        layer.closeAll();
                        layer.msg("保存成功");
                        setTimeout(function () {
                            history.go(-1);
                        }, 1000)
                    }else{
                        layer.msg(result.msg, {time: 1500});
                    }
                }
            });
        }else{
            layer.closeAll();
            if(srcs.length > 0){
                layer.msg("商品图片上传失败");
            }else{
                layer.msg("请上传商品图片");
            }
        }
    });
</script>

<script>
    //配置项：详情地址、添加地址
    var detailUrl = SERVER_URL+"/shopGoods/detail";
    var editUrl = SERVER_URL+"/shopGoods/edit";

    layui.use(['jquery', 'form'], function() {
        var $ = layui.jquery;
        var form = layui.form;

        //配置项：初始化表单数据
        function initForm(data) {
            $("input[name='goodsName']").val(data.goodsName);
            $("input[name='goodsTitle']").val(data.goodsTitle);
            $("input[name='goodsPrice']").val(data.goodsPrice);
            $("input[name='goodsStock']").val(data.goodsStock);

            var goodsImage = data.goodsImage.split(",");
            var str = "";
            for(var i in goodsImage){
                var li = '<div class="uploader-item">';
                li += '		<input name="upload-img-src" type="hidden" value="'+goodsImage[i]+'"/>';
                li += '		<img class="upload-img" src="'+goodsImage[i]+'"/>';
                li += '		<img class="del-img" src="/plugins/img/del.png" onClick="del(this)"/>'
                li += '   </div>';
                str += li;
                imgNum ++;
            }
            $(".uploader-list").append(str);
        }

        //判断新增or修改
        if(urlParam("id")){
            $.ajax({
                type: 'GET',
                url: detailUrl,
                data: {id: urlParam("id")},
                success: function (result) {
                    if(result.code == 20000){
                        initForm(result.data);
                    }else{
                        layer.msg(result.msg, {time: 1500});
                    }
                }
            });
        }

        //新增or修改
        form.on('submit(contentForm)', function(data){
            uploader.upload();
            layer.load(1, {
                shade: [0.2,'#000'] //0.1透明度的白色背景
            });
            return false;
        });
    });

    //地址栏参数
    function urlParam(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)	return unescape(r[2]);
        return null;
    }
</script>
</body>

</html>
